/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.ikame.android.boojtran.truyenbua.utility;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.SharedPreferences;

public class CStore {
	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	private boolean first;
	private int pic;
	private String showedStr;
	private String storyStr;

	private final String KEY_FIRSTTIME = "firsttime";
	private final String KEY_CURPIC = "pic";
	private final String KEY_SHOWEDPIC = "showed";
	private final String KEY_READSTORY = "read";

	public CStore(Activity activity) {
		prefs = activity.getPreferences(android.content.Context.MODE_PRIVATE);
		this.editor = prefs.edit();
		first = prefs.getBoolean(KEY_FIRSTTIME, true);
		pic = prefs.getInt(KEY_CURPIC, -1);
		showedStr = prefs.getString(KEY_SHOWEDPIC, "");
		storyStr = prefs.getString(KEY_READSTORY, "");
	}

	private void Save() {
		editor.putBoolean(KEY_FIRSTTIME, first);
		editor.putInt(KEY_CURPIC, pic);
		editor.putString(KEY_SHOWEDPIC, showedStr);
		editor.putString(KEY_READSTORY, storyStr);
		editor.commit();
	}

	public int getPic() {
		return pic;
	}

	public void setPic(int pic) {
		this.pic = pic;
		Save();
	}

	// showed pic
	public void setShowedArr(ArrayList<Integer> showedArr) {
		showedStr = getShowedStr(showedArr);
		Save();
	}

	private String getShowedStr(ArrayList<Integer> showedArr) {
		String result = "";
		for (int i : showedArr) {
			result = result + i + " ";
		}
		return result.trim();
	}

	public ArrayList<Integer> getShowedArr() {
		return getIntArr(showedStr, " ");
	}

	public String getShowedStr() {
		return showedStr;
	}

	public void setShowedStr(String showedStr) {
		this.showedStr = showedStr;
		Save();
	}

	// fun story
	public void setStoryArr(ArrayList<Integer> storyArr) {
		this.storyStr = getStoryStr(storyArr);
		Save();
	}

	private String getStoryStr(ArrayList<Integer> storyArr) {
		String result = "";
		for (int i : storyArr) {
			result = result + i + " ";
		}
		return result.trim();
	}

	public ArrayList<Integer> getStoryArr() {
		return getIntArr(storyStr, " ");
	}

	public String getStoryStr() {
		return storyStr;
	}

	public void setStoryStr(String storyStr) {
		this.storyStr = storyStr;
		Save();
	}

	private ArrayList<Integer> getIntArr(String str, String token) {
		ArrayList<Integer> result = new ArrayList<Integer>();
		StringTokenizer tokens = new StringTokenizer(str, token);
		while (tokens.hasMoreElements()) {
			int img = -1;
			try {
				img = Integer.parseInt(tokens.nextElement().toString().trim());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			if (img != -1)
				result.add(img);
		}
		return result;
	}

	public boolean isFirstTime() {
		return first;
	}

	public void setFirstTime(boolean first) {
		this.first = first;
		Save();
	}
}
